package com.qubaopen.survey.service;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.qubaopen.core.beans.ServiceException;
import com.qubaopen.core.utils.SecurityUtils;
import com.qubaopen.survey.dao.MemberBasicDao;
import com.qubaopen.survey.domain.MemberBasic;

@Service("userService")
public class UserService {

	private static final String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
			+ "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";

	@Autowired
	MemberBasicDao memberBasicDao;

	@Transactional
	public JSONObject authenticate(String username, String password)
			throws ServiceException {
		MemberBasic memberBasic = null;
		JSONObject response = new JSONObject();
		try {
			password = SecurityUtils.md5(password);
			if (StringUtils.isNumeric(username)) {
				memberBasic = memberBasicDao.authenticateByPhoneNumber(
						username, password);
			} else if (username.matches(EMAIL_PATTERN)) {
				memberBasic = memberBasicDao.authenticateByPhoneNumber(
						username, password);
			} else {
				memberBasic = memberBasicDao.authenticate(username, password);
			}
			if (memberBasic != null) {
				response.put("success", "1");
			} else {
				response.put("success", "0");
			}

		} catch (Exception e) {
			response.put("success", "0");
			throw new ServiceException("username or password error");
		}

		return response;
	}

}
